package com.cadre.common.utils.oldutil;

import cn.hutool.core.util.RandomUtil;
import com.cadre.common.exception.CadreException;
import com.cadre.common.utils.common.DateUtils;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

@Component
/* loaded from: DocBatchPrint.class */
public class DocBatchPrint {
    @Autowired
    ReportConfig reportConfig;
    private String pathFolder;
    private String mergeword;
    private String destpdf;
    private List<File> sortWordList;
    private List<String> srcList;
    private static final String fileName = "干部任免审批表";

    public void printWord(List<Map<String, Object>> mapList, ReportConfig reportConfig, HttpServletResponse response) {
        String relativePath = WordUtils.class.getClassLoader().getResource("tempfile/temp.txt").getPath();
        this.pathFolder = relativePath.substring(0, relativePath.lastIndexOf("/")) + "/" + DateUtils.format(new Date()) + "/" + RandomUtil.getRandom() + "/";
        this.pathFolder = this.pathFolder.substring(1, this.pathFolder.length());
        this.mergeword = this.pathFolder + "干部任免审批表合并表.docx";
        this.destpdf = this.pathFolder + "干部任免审批表合并表.pdf";
        this.sortWordList = new ArrayList();
        File folder = new File(this.pathFolder);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        try {
            try {
                for (Map<String, Object> map : mapList) {
                    File file = new File(this.pathFolder + fileName + "_" + map.get("oid").toString() + ".docx");
                    this.sortWordList.add(file);
                    XWPFDocument document = new XWPFDocument(new ClassPathResource(reportConfig.getWorldTmp()).getInputStream());
                    String str = map.get("a01_a0814") == null ? "" : map.get("a01_a0814").toString().trim();
                    if (WordUtils.ismergeCell(str)) {
                        WordUtils.mergeCell(document, str, 4, 4);
                    } else {
                        String[] school = WordUtils.splitstr(str);
                        if (school.length > 0) {
                            map.put("a01_a0401", school[0]);
                            map.put("a01_a0402", school[1]);
                        }
                    }
                    String strcel = map.get("a01_a0903") == null ? "" : map.get("a01_a0903").toString().trim();
                    if (WordUtils.ismergeCell(strcel)) {
                        WordUtils.mergeCell(document, strcel, 6, 4);
                    } else {
                        String[] school2 = WordUtils.splitstr(strcel);
                        map.put("a01_a0501", school2[0]);
                        map.put("a01_a0502", school2[1]);
                    }
                    OutputStream out = new FileOutputStream(file);
                    WordUtils.replaceTable(document, map);
                    document.write(out);
                    out.flush();
                    out.close();
                }
                mergeDoc();
                MergePDF.wordToPdf(this.mergeword, this.destpdf);
                WordUtils.showPdf(response, this.destpdf);
                WordUtils.deleteDir(this.pathFolder);
            } catch (Exception e) {
                e.printStackTrace();
                throw new CadreException(ResultEnum.OFFICE_ERROR);
            }
        } catch (Throwable th) {
            WordUtils.deleteDir(this.pathFolder);
            throw th;
        }
    }

    public void downWord(List<Map<String, Object>> mapList, ReportConfig reportConfig, HttpServletResponse response) {
        String relativePath = WordUtils.class.getClassLoader().getResource("tempfile/temp.txt").getPath();
        String finpath = relativePath.substring(0, relativePath.lastIndexOf("/"));
        String tp = DateUtils.format(new Date());
        this.srcList = new ArrayList();
        this.pathFolder = finpath + "/" + tp + "/" + RandomUtil.getRandom() + "/";
        this.pathFolder = this.pathFolder.substring(1, this.pathFolder.length());
        File folder = new File(this.pathFolder);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        try {
            try {
                for (Map<String, Object> map : mapList) {
                    File file = new File(this.pathFolder + fileName + "_" + map.get("a01_a0101").toString() + ".docx");
                    this.srcList.add(this.pathFolder + file.getName());
                    XWPFDocument document = new XWPFDocument(new ClassPathResource(reportConfig.getWorldTmp()).getInputStream());
                    String str = map.get("a01_a0814") == null ? "" : map.get("a01_a0814").toString().trim();
                    if (WordUtils.ismergeCell(str)) {
                        WordUtils.mergeCell(document, str, 4, 4);
                    } else {
                        String[] school = WordUtils.splitstr(str);
                        if (school.length > 0) {
                            map.put("a01_a0401", school[0]);
                            map.put("a01_a0402", school[1]);
                        }
                    }
                    String strcel = map.get("a01_a0903") == null ? "" : map.get("a01_a0903").toString().trim();
                    if (WordUtils.ismergeCell(strcel)) {
                        WordUtils.mergeCell(document, strcel, 6, 4);
                    } else {
                        String[] school2 = WordUtils.splitstr(strcel);
                        map.put("a01_a0501", school2[0]);
                        map.put("a01_a0502", school2[1]);
                    }
                    OutputStream out = new FileOutputStream(file);
                    WordUtils.replaceTable(document, map);
                    document.write(out);
                    out.flush();
                    out.close();
                }
                FileUtils.downloadZipFiles(response, this.srcList, "干部任免审批表.zip");
                WordUtils.deleteDir(this.pathFolder);
            } catch (Exception e) {
                e.printStackTrace();
                throw new CadreException(ResultEnum.OFFICE_ERROR);
            }
        } catch (Throwable th) {
            WordUtils.deleteDir(this.pathFolder);
            throw th;
        }
    }

    public void mergeDoc() {
        List<File> srcfile = this.sortWordList;
        try {
            OutputStream dest = new FileOutputStream(this.mergeword);
            ArrayList<XWPFDocument> documentList = new ArrayList<>();
            XWPFDocument doc = null;
            for (int i = 0; i < srcfile.size(); i++) {
                documentList.add(new XWPFDocument(OPCPackage.open(new FileInputStream(srcfile.get(i).getPath()))));
            }
            for (int i2 = 0; i2 < documentList.size(); i2++) {
                doc = documentList.get(0);
                if (i2 != 0) {
                    insertNextPageChar(doc);
                    appendBody(doc, documentList.get(i2));
                }
            }
            doc.write(dest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void appendBody(XWPFDocument src, XWPFDocument append) throws Exception {
        CTBody src1Body = src.getDocument().getBody();
        CTBody src2Body = append.getDocument().getBody();
        List<XWPFPictureData> allPictures = append.getAllPictures();
        Map<String, String> map = new HashMap<>();
        for (XWPFPictureData picture : allPictures) {
            map.put(append.getRelationId(picture), src.addPictureData(picture.getData(), 6));
        }
        appendBody(src1Body, src2Body, map);
    }

    private void appendBody(CTBody src, CTBody append, Map<String, String> map) throws Exception {
        XmlOptions optionsOuter = new XmlOptions();
        optionsOuter.setSaveOuter();
        String appendString = append.xmlText(optionsOuter);
        String srcString = src.xmlText();
        String prefix = srcString.substring(0, srcString.indexOf(">") + 1);
        String mainPart = srcString.substring(srcString.indexOf(">") + 1, srcString.lastIndexOf("<"));
        String sufix = srcString.substring(srcString.lastIndexOf("<"));
        String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
        if (map != null && !map.isEmpty()) {
            for (Map.Entry<String, String> set : map.entrySet()) {
                addPart = addPart.replace(set.getKey(), set.getValue());
            }
        }
        src.set(CTBody.Factory.parse(prefix + mainPart + addPart + sufix));
    }

    public void insertNextPageChar(XWPFDocument doc) {
        CTBody body = doc.getDocument().getBody();
        CTSectPr sectPr = doc.createParagraph().getCTP().addNewPPr().addNewSectPr();
        CTSectPr bodySectPr = body.getSectPr();
        sectPr.setPgSz(bodySectPr.getPgSz());
        sectPr.setPgMar(bodySectPr.getPgMar());
        sectPr.setCols(bodySectPr.getCols());
        sectPr.setDocGrid(bodySectPr.getDocGrid());
    }
}
